const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    const { 
      status = null,
      page = 1,
      pageSize = 10
    } = event
    
    // 直接使用openid作为用户标识
    const userOpenid = openid
    
    // 构建查询条件
    let queryConditions = {
      userId: userOpenid
    }
    
    // 根据状态筛选
    if (status && status !== 'all') {
      queryConditions.status = status
    }
    
    let query = db.collection('orders').where(queryConditions)
    
    // 分页查询
    const skip = (page - 1) * pageSize
    const result = await query
      .orderBy('createdAt', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理订单数据，格式化时间和状态
    const orders = result.data.map(order => {
      // 格式化创建时间
      const createdAt = order.createdAt
      let formattedTime = ''
      if (createdAt) {
        const date = new Date(createdAt)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hour = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        formattedTime = `${year}-${month}-${day} ${hour}:${minute}`
      }
      
      // 计算商品总数量
      const totalQuantity = order.items ? order.items.reduce((sum, item) => sum + item.quantity, 0) : 0
      
      // 获取第一个商品作为主要展示商品
      const mainProduct = order.items && order.items.length > 0 ? order.items[0] : null
      
      return {
        ...order,
        formattedTime,
        totalQuantity,
        mainProduct,
        statusText: getStatusText(order.status)
      }
    })
    
    return {
      success: true,
      data: orders,
      total: result.data.length
    }
    
  } catch (error) {
    console.error('获取订单列表失败:', error)
    return {
      success: false,
      message: error.message || '获取订单列表失败'
    }
  }
}

// 格式化订单状态显示文本
function getStatusText(status) {
  const statusMap = {
    'pending_payment': '待付款',
    'pending_shipment': '待发货', 
    'pending_receipt': '待收货',
    'pending_review': '待评价',
    'paid': '已支付',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知状态'
}